import { login, logout, phoneCodeLogin, register } from '@/api/user'
import { getRouteIds, getRoutes } from '@/api/role'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { Message } from 'element-ui'

const state = {
  token: getToken(),
  userBase: null,
  name: '',
  avatar: '',
  // introduction: '',
  roles: [],
  currentRole: null
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  // SET_INTRODUCTION: (state, introduction) => {
  //   state.introduction = introduction
  // },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USER_BASE: (state, userBase) => {
    state.userBase = userBase
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_CURRENT_ROLE: (state, currentRole) => {
    state.currentRole = currentRole
  }
}

const actions = {
  // go to register page
  gotoRegisterPage({ commit }) {
    return new Promise((resolve, reject) => {
      resolve()
    })
  },
  // user register
  register({ commit }, registerInfo) {
    return new Promise((resolve, reject) => {
      register(registerInfo).then(response => {
        if (response.status === 200 && response.data.status === 200) {
          const resInfo = { status: response.status, msg: '注册成功' }
          resolve(resInfo)
        } else {
          const resInfo = { status: response.status, msg: response.data.msg }
          resolve(resInfo)
        }
      }).catch(error => {
        console.error(error)
        reject(error)
      })
    })
  },
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username, password: password }).then(response => {
        if (response.status === 200 && response.data) {
          const data = response.data.userInfo
          const useBaseInfo = {
            username: data.username,
            nickname: data.nickname,
            email: data.email,
            phoneNum: data.phoneNum
          }
          window.sessionStorage.setItem('userInfo', JSON.stringify(useBaseInfo))
          const { roles, currentRole } = data
          roles[0] = currentRole
          commit('SET_TOKEN', useBaseInfo)
          commit('SET_NAME', useBaseInfo.username)
          setToken(currentRole.id)
          commit('SET_ROLES', roles)
          window.sessionStorage.setItem('roles', JSON.stringify(roles))
          commit('SET_CURRENT_ROLE', currentRole)
          window.sessionStorage.setItem('currentRole', currentRole)
          // commit('SET_AVATAR', avtar)
          getRouteIds(currentRole.id).then(response => {
            if (response.status === 200 && response.data.status === 200) {
              const routeIds = response.data['data']
              window.sessionStorage.setItem('routeData', JSON.stringify(routeIds))
            } else {
              Message.error('response.status=' + response.status + 'response.text=' + response.text)
            }
          })
          resolve(useBaseInfo)
        } else {
          Message.error('user login failed')
          resolve()
        }
      }).catch(error => {
        console.error(error)
        reject(error)
      })
    })
  },
  // phone code login
  mobileLogin({ commit }, phoneParam) {
    const { phoneNo, phoneCode } = phoneParam
    return new Promise((resolve, reject) => {
      phoneCodeLogin({ phoneNo: phoneNo, phoneCode: phoneCode }).then(res => {
        if (res.status === 200 && res.data) {
          const data = res.data.userInfo
          const useBaseInfo = {
            username: data.username,
            nickname: data.nickname,
            phoneNum: data.phoneNum,
            email: data.email
          }
          window.sessionStorage.setItem('userInfo', JSON.stringify(useBaseInfo))
          const { roles, currentRole } = data
          roles[0] = currentRole
          commit('SET_TOKEN', useBaseInfo)
          commit('SET_NAME', useBaseInfo.username)
          setToken(currentRole.id)
          commit('SET_ROLES', roles)
          window.sessionStorage.setItem('roles', JSON.stringify(roles))
          commit('SET_CURRENT_ROLE', currentRole)
          window.sessionStorage.setItem('currentRole', currentRole)
          // commit('SET_AVATAR', avtar)
          getRouteIds(currentRole.id).then(response => {
            if (response.status === 200 && response.data.status === 200) {
              const routeIds = response.data['data']
              window.sessionStorage.setItem('routeData', JSON.stringify(routeIds))
            } else {
              Message.error('response.status=' + response.status + 'response.text=' + response.text)
            }
          })
          resolve(useBaseInfo)
        } else {
          Message.error('phone code login failed')
          resolve()
        }
      }).catch(error => {
        console.error(error)
        reject(error)
      })
    })
  },
  // get user info
  /**
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }
        const { roles, name, avatar, introduction } = data
        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  }, */
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then(res => {
        if (res.status === 200) {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_NAME', '')
          commit('SET_CURRENT_ROLE', null)
          window.sessionStorage.removeItem('userInfo')
          window.sessionStorage.removeItem('routeIds')
          window.sessionStorage.removeItem('roles')
          window.sessionStorage.removeItem('currentRole')
          removeToken()
          resetRouter()
          // reset visited views and cached views
          // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
          dispatch('tagsView/delAllViews', null, { root: true })
          Message.info('退出登录成功')
          resolve()
        } else {
          reject('退出登录失败')
        }
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },
  // 切换角色
  changeRoles({ dispatch }, roleId) {
    return new Promise(async resolve => {
      resetRouter()
      // generate accessible routes map based on roles
      getRoutes(roleId).then(response => {
        if (response.status === 200 && response.data.status === 200) {
          const dynamicRouteData = response.data['data']
          window.sessionStorage.setItem('routeData', JSON.stringify(dynamicRouteData))
          // dynamically add accessible routes
          dispatch('permission/generateRoutes', dynamicRouteData)
          // reset visited views and cached views
          dispatch('tagsView/delAllViews', null)
        } else {
          Message.error('response.status=' + response.status + 'response.text=' + response.text)
        }
      })
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
